package andersonb.spring.social.config;

import javax.inject.Inject;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ControladorFacebook {
	@Inject
	private Facebook facebook;

	@RequestMapping("/facebook")
	public ModelAndView index() {
		ModelAndView resultado = new ModelAndView("facebook/index");
		resultado.addObject("autorizado", facebook.isAuthorized());

		if (facebook.isAuthorized()) {
			resultado.addObject("perfil", facebook.userOperations()
					.getUserProfile());
			resultado
					.addObject("feed", facebook.feedOperations().getHomeFeed());
		}

		return resultado;
	}

	@RequestMapping(value = "/facebook/profilePicture", method = RequestMethod.GET)
	public ResponseEntity<byte[]> profilePicture() {
		byte[] array = new byte[1];
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.IMAGE_JPEG);

		if (facebook.isAuthorized()) {
			array = facebook.userOperations().getUserProfileImage();
		}

		return new ResponseEntity<byte[]>(array, headers, HttpStatus.OK);
	}

	@RequestMapping(value = "/facebook/enviar", method = RequestMethod.POST)
	public ModelAndView enviar(@RequestParam String texto) {
		facebook.feedOperations().updateStatus(texto);
		return index();
	}
}
